<template>
  <d2-container>
    <el-row>
      <el-col :lg="12">
        <el-form ref="detailForm" :model="detailForm" :rules="rules" label-width="100px">
          <el-form-item label="标题" prop="title">
            <el-input placeholder="标题" v-model="detailForm.title"></el-input>
          </el-form-item>
          <el-form-item label="子标题" prop="subtitle">
            <el-input placeholder="子标题" v-model="detailForm.subtitle"></el-input>
          </el-form-item>
          <el-form-item label="门店" prop="storeName">
            <el-input placeholder="门店" v-model="detailForm.storeName" readonly @focus="fnOpenPopup"></el-input>
          </el-form-item>
          <el-form-item v-if="false" disabled label="有效期">
            <el-date-picker
              v-model="detailForm.expries"
              style="width: 100%"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="链接" prop="refLink">
            <museLink v-model="detailForm.refLink"></museLink>
            <!--                        <el-input placeholder="小程序内跳转" v-model="detailForm.refLink[0].target"></el-input>-->
            <!--                        <el-input placeholder="站外跳转" v-model="detailForm.refLink[1].target"></el-input>-->
          </el-form-item>
          <el-form-item label="列表缩略图">
            <el-upload
              class="avatar-uploader"
              :http-request="(file) => handleAvatarSuccess(file, 'imageUrl')"
              :show-file-list="false"
            >
              <img v-if="detailForm.imageUrl" :src="detailForm.imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="首页长图">
            <el-upload
              class="avatar-uploader"
              :http-request="(file) => handleAvatarSuccess(file, 'showImageLarge')"
              :show-file-list="false"
            >
              <img v-if="detailForm.showImageLarge" :src="detailForm.showImageLarge" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="首页短图">
            <el-upload
              class="avatar-uploader"
              :http-request="(file) => handleAvatarSuccess(file, 'showImageSmall')"
              :show-file-list="false"
            >
              <img v-if="detailForm.showImageSmall" :src="detailForm.showImageSmall" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="轮播图" prop="images">
            <banner v-model="detailForm.images"></banner>
          </el-form-item>
          <el-form-item label="详情" prop="detail">
            <simpleRich v-model="detailForm.detail"></simpleRich>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('detailForm')">确定</el-button>
            <el-button @click="resetForm('detailForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-dialog title="门店列表" :visible.sync="dialogDataVisible">
      <el-table :data="tableData" width="100%" ref="ref_table" @select="handleSelectionChange">
        <el-table-column fixed type="selection" width="55" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="brief" label="简介">
          <template slot-scope="{row: {brief}}">
            <span>{{brief | subStr(10)}}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="muse_pagination"
        :background="true"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paging.page"
        :page-sizes="paging.pageSizeAry"
        :page-size="paging.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paging.total"
      ></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fnClosePopup">取 消</el-button>
        <el-button type="primary" @click="fnSaveChoosed">确 定</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import simpleRich from "@/components/muse/simple-rich/simple-rich";
import banner from "@/components/muse/banner/banner";
import museLink from "@/components/muse/muse-link/muse-link";
import tableMixin from "../mixins/tableMixin";
import uploadMixin from "../mixins/uploadMixin";
import { changeActivity, getOneActivity, getStoreList } from "@/api/admin";
export default {
  name: "changeActivity",
  components: {
    simpleRich,
    banner,
    museLink,
  },
  mixins: [uploadMixin, tableMixin],
  data() {
    return {
      id: "",
      oldDetailForm: {},
      oldStoreList: [],
      detailForm: {
        title: "",
        subtitle: "",
        store: [],
        storeName: "",
        images: [],
        detail: "",
        refLink: {},
        imageUrl: "",
        showImageLarge: "",
        showImageSmall: "",
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        subtitle: [
          { required: true, message: "请输入副标题", trigger: "blur" },
        ],
        storeName: [
          { required: false, message: "请选择商店", trigger: "blur" },
        ],
        detail: [{ required: true, message: "请输入详情", trigger: "blur" }],
        images: [{ required: true, message: "请输入图片", trigger: "blur" }],
        refLink: [{ required: true, message: "请输入链接", trigger: "blur" }],
      },
      tableData: [],
      choosedDataObj: [],
      dialogDataVisible: false,
    };
  },
  created() {
    this.id = this.$route.query.id;
    if (this.id) {
      this.getOneActivity();
    }
  },
  methods: {
    // 得到活动详情
    async getOneActivity() {
      const res = await getOneActivity({ id: this.id });
      this.detailForm = res.data;
      // this.detailForm.storeName = this.detailForm.store
      this.choosedDataObj = this.detailForm.store;
      this.oldStoreList = this.choosedDataObj;
      this.fnFormatData();
      this.$nextTick(() => {
        this.detailForm.refLink = this.detailForm.refLink[0];
      });
    },
    // 单图片上传
    async handleAvatarSuccess(file, type, index) {
      const url = await this.fnUpload(file);
      this.detailForm[type] = url;
      this.$forceUpdate();
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.detailForm.refLink = [this.detailForm.refLink];
          if (this.id) {
            this.detailForm["id"] = this.id;
          }
          const res = await changeActivity(this.detailForm);
          this.$router.push({ name: "activityList" });
        } else {
          return false;
        }
      });
    },
    // 表单重置
    resetForm(formName) {
      this.$nextTick(() => {
        this.detailForm.refLink = "";
        this.detailForm.detail = "";
      });
      this.$refs[formName].resetFields();
    },

    // 打开门店弹框
    fnOpenPopup() {
      this.dialogDataVisible = true;
      this.getTableData();
    },
    fnClosePopup() {
      this.dialogDataVisible = false;
      this.choosedDataObj = [];
      this.choosedDataObj = this.oldStoreList;
    },
    // 获得门店列表
    async getTableData(value, type) {
      let params = {
        page:
          type === "page"
            ? value
              ? value
              : this.paging.page
            : this.paging.page,
        pageSize:
          type === "pageSize"
            ? value
              ? value
              : this.paging.pageSize
            : this.paging.pageSize,
      };
      const {
        code,
        data: { total, currentPage, data, pageSize },
      } = await getStoreList(params);
      this.paging.total = total;
      this.paging.pageSize = pageSize;
      this.paging.page = currentPage;
      this.tableData = data;

      const showAry = this.tableData.filter((item) => {
        for (let i = 0; i < this.choosedDataObj.length; i++) {
          if (item._id === this.choosedDataObj[i]._id) {
            return true;
          }
        }
      });

      this.$nextTick(() => {
        showAry.forEach((item) => {
          this.$refs.ref_table.toggleRowSelection(item, true);
        });
      });
    },
    /**
     * @description:  单选时使用
     * @param {type}
     * @return:
     */
    handleRadioTable(value) {
      console.log(123, value);
      this.choosedDataObj = value;
    },
    fnSaveChoosed() {
      // 单选时使用
      //   this.detailForm.store = this.choosedDataObj._id
      // this.detailForm.storeName = this.choosedDataObj.name
      this.fnFormatData();
      this.fnClosePopup();
    },
    /**
     * @description: 当多选门店是处理数据
     * @param {type}
     * @return:
     */
    fnFormatData() {
      this.detailForm.store = [];
      this.detailForm.storeName = [];
      this.choosedDataObj.forEach((item) => {
        this.detailForm.store.push(item._id);
        this.detailForm.storeName.push(item.name);
      });
      this.oldStoreList = this.choosedDataObj;
    },
    // 弹框选择项编辑
    handleSelectionChange(valueAry, value) {
      // this.choosedDataObj = valueAry;

      this.choosedDataObj = this.choosedDataObj.map((item) => {
        return JSON.stringify(item);
      });
      if (this.choosedDataObj.indexOf(JSON.stringify(value)) > -1) {
        this.choosedDataObj.splice(
          this.choosedDataObj.indexOf(JSON.stringify(value)),
          1
        );
      } else {
        this.choosedDataObj.push(JSON.stringify(value));
      }
      this.choosedDataObj = this.choosedDataObj.map((item) => {
        return JSON.parse(item);
      });
    },
  },
};
</script>

<style scoped>
.from_width {
  width: 40%;
}
</style>
